//index.js
//获取应用实例
const app = getApp();
var Bmob = require('../../utils/bmob.js');
var that;
// 最大行数
var max_row_height = 5;
// 行高
var cart_offset = 90;
// 底部栏偏移量
var product_row_height = 49;
Page({
  data: {
    categoryStates: [],
    cartData: {},
    cartObjects: [],
    maskVisual: 'hidden',
    amount: 0,
    quantity:0,
    root: app.rootUrl,
    shop: {},
    notice: {},
    departId: '',
    circular: true,
    //是否显示画板指示点，根据图片数量自动生成多少个圆点
    indicatorDots: true,
    //选中点的颜色
    //是否竖直
    vertical: false,
    //是否自动切换
    autoplay: true,
    //自动切换的间隔
    interval: 3000,
    //滑动动画时长毫秒
    duration: 1000,
    //所有图片的高度
    imgheights: [],
    //图片宽度
    imgwidth: 320,
    //默认
    current: 0,
  },
  onLoad: function () {
    that = this;
    that.cascadeToggle()
  },
  onShow: function () {
    that.showCar();
  },
  saveCar: function (e) {
    var productid = e.currentTarget.dataset.index;
    wx.request({
      url: app.rootUrl + '/api/saveCar',
      data: {'productId':productid},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      success: function (res) {
        that.showCar();
      }
    });
  },
  editCar: function (e) {
    var productid = e.currentTarget.dataset.index;
    var count = e.currentTarget.dataset.count;
    wx.request({
      url: app.rootUrl + '/api/editCar',
      data: { 'productId': productid, 'count': count},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      success: function (res) {
        that.showCar();
      }
    });
  },
  productDetail: function (e){
    var index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '../detail/detail?productid=' + index,
    })
  },
  saveOrder: function () {
    if(that.data.amount == 0){
      wx.showToast({
        title: '请选购',
        image: '../../images/info.png',
      })
      return null;
    }
    wx.navigateTo({
    url: '../checkout/checkout',
    })
  },
  add: function (e) {
    //debugger
    // 所点商品id
    var productId = e.currentTarget.dataset.productId;
    // console.log(productId);
    // 读取目前购物车数据
    var cartData = that.data.cartData;
    // 获取当前商品数量
    var productCount = cartData[productId] ? cartData[productId] : 0;
    // 自增1后存回
    cartData[productId] = ++productCount;
    // 设值到data数据中
    that.setData({
      cartData: cartData
    });
    // 转换成购物车数据为数组
    that.cartToArray(productId);
  },
  subtract: function (e) {
    // 所点商品id
    var productId = e.currentTarget.dataset.productId;
    // 读取目前购物车数据
    var cartData = that.data.cartData;
    // 获取当前商品数量
    var productCount = cartData[productId];
    // 自减1
    --productCount;
    // 减到零了就直接移除
    if (productCount == 0) {
      delete cartData[productId]
    } else {
      cartData[productId] = productCount;
    }
    // 设值到data数据中
    that.setData({
      cartData: cartData
    });
    // 转换成购物车数据为数组
    that.cartToArray(productId);
  },
  cartToArray: function (productId) {
    // 需要判断购物车数据中是否已经包含了原商品，从而决定新添加还是仅修改它的数量
    debugger
    var cartData = that.data.cartData;
    var cartObjects = that.data.cartObjects;
    var query = new Bmob.Query('product');
    // 查询对象
    query.get(productId).then(function (product) {
      // 从数组找到该商品，并修改它的数量
      for (var i = 0; i < cartObjects.length; i++) {
        if (cartObjects[i].product.id == productId) {
          // 如果是undefined，那么就是通过点减号被删完了
          if (cartData[productId] == undefined) {
            cartObjects.splice(i, 1);
          } else {
            cartObjects[i].quantity = cartData[productId];
          }
          that.setData({
            cartObjects: cartObjects
          });
          // 成功找到直接返回，不再执行添加
          that.amount();
          return;
        }
      }
      // 添加商品到数组
      var cart = {};
      cart.product = product;
      cart.quantity = cartData[productId];
      cartObjects.push(cart);
      that.setData({
        cartObjects: cartObjects
      });
      // 因为请求网络是异步的，因此汇总在此，上同
      that.amount();
    });
  },
  cascadeToggle: function () {
   //wx.navigateTo({
     //url: '../checkout/checkout',
   //})
    if (that.data.maskVisual == 'show') {
      that.cascadeDismiss();
    } else {
      that.cascadePopup();
      that.showCar();
    }
    
  },
  showCar: function(){
    wx.request({
      url: app.rootUrl + '/api/showCar',
      data: {},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      success: function (res) {
        that.setData({
          amount: res.data.total,
          quantity: res.data.count,
          cartObjects: res.data.carObjList
        });
      }
    })
  },
  cascadePopup: function () {
    // 购物车打开动画
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-in-out',
    });
    that.animation = animation;
    // scrollHeight为商品列表本身的高度
    var scrollHeight = (that.data.cartObjects.length <= max_row_height ? that.data.cartObjects.length : max_row_height) * product_row_height;
    // cartHeight为整个购物车的高度，也就是包含了标题栏与底部栏的高度
    var cartHeight = scrollHeight + cart_offset;
    animation.translateY(- cartHeight).step();
    that.setData({
      animationData: that.animation.export(),
      maskVisual: 'show',
      scrollHeight: scrollHeight,
      cartHeight: cartHeight
    });
    // 遮罩渐变动画
    var animationMask = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
    });
    that.animationMask = animationMask;
    animationMask.opacity(0.8).step();
    that.setData({
      animationMask: that.animationMask.export(),
    });
  },
  cascadeDismiss: function () {
    // 购物车关闭动画
    that.animation.translateY(that.data.cartHeight).step();
    that.setData({
      animationData: that.animation.export()
    });
    // 遮罩渐变动画
    that.animationMask.opacity(0).step();
    that.setData({
      animationMask: that.animationMask.export(),
    });
    // 隐藏遮罩层
    that.setData({
      maskVisual: 'hidden'
    });
  },
  imageLoad: function(e) { //获取图片真实宽度
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比
      ratio = imgwidth / imgheight;
    //计算的高度值
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  bindchange: function(e) {
    // console.log(e.detail.current)
    this.setData({
      current: e.detail.current
    })
  }
})
